﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using GigaSite.Domain.DAL;
using GigaSite.Domain.Infrastucture;
using GigaSite.Domain.Interfaces.Repositories;
using GigaSite.Domain.IoC;
using GigaSite.Web.Classes;
using GigaSite.Web.Models;
using GigaSite.Web.Models.Validators;

namespace GigaSite.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        /// <summary>
        /// Запуск приложение
        /// </summary>
        protected void Application_Start()
        {
            Global.Logger.Info("Инициализация приложения");

            // MVC Initialization
            MvcInitialization();

            // IoC initialization
            IoCInitialization();
        }

        /// <summary>
        /// Начала сессии пользователя
        /// </summary>
        protected void Session_Start()
        {
            // Контекст
            var context = HttpContext.Current;

            // Ищем авторизационную куку
            var authCookie = context.Request.Cookies["auth"];
            if (authCookie != null)
            {
                var identity = authCookie["identity"];
                var pass = authCookie["pass"];

                var repository = Locator.GetService<IUsersRepository>();
                var user = repository.GetUserByIdentityAndPasswordHash(identity, pass);
                if (user != null)
                {
                    context.Session["CurrentUser"] = user.Id;
                    user.LastLogin = DateTime.Now;
                    repository.SubmitChanges();
                    Global.Logger.Info(String.Format("Начало сессии пользователя {0}",identity));
                }
                else
                {
                    Global.Logger.Warn(String.Format("Попытка взлома сессии пользователя {0}",identity));
                    context.Response.Cookies.Remove("auth");
                }
            }
        }

        /// <summary>
        /// Инициализация IoC контейнера
        /// </summary>
        private void IoCInitialization()
        {
            Locator.Init(new DALRegistrationModule(), new InfrastructureRegistrationModule());
            //DependencyResolver.SetResolver(new NinjectDependencyResolver(Locator.Container));

            Global.Logger.Info("IoC контейнер проинициализирован");
        }

        /// <summary>
        /// Инициализация приложения, связанная с Mvc
        /// </summary>
        private void MvcInitialization()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            RegisterModelValidators();

            Global.Logger.Info("MVC компоненты проинициализированы");
        }

        /// <summary>
        /// Регистрирует валидаторы для моделей
        /// </summary>
        private void RegisterModelValidators()
        {
            ModelValidatorsFactory.BindModelToValidator<RegisterModel,RegisterModelValidator>();
            ModelValidatorsFactory.BindModelToValidator<LogOnModel,LogOnModelValidator>();
        }
    }
}